package com.example.order.controller;
import java.math.BigDecimal;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.example.order.bean.Order;
import com.example.order.properties.OrderProperties;
import com.example.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

//@CrossOrigin
@Slf4j
//@RequestMapping("/api/order")
//@RefreshScope //自动刷新配置
@RestController
public class OrderController {

    @Autowired
    OrderService orderService;

//    @Value("${order.timeout}")
//    String orderTimeout;
//
//    @Value("${order.auto-confirm}")
//    String orderAutoConfirm;
    @Autowired
    OrderProperties orderProperties;

    @GetMapping("/config")
    public String config() {
        return "order.timeout=" + orderProperties.getTimeout() + ": auto-confirm=" + orderProperties.getAutoConfirm()
                + " order.db-url=" + orderProperties.getDbUrl();
    }

    @GetMapping("/create")
    public Order createOrder(@RequestParam("userId") Long userId,
                             @RequestParam("productId") Long productId) {
        Order order = orderService.createOrder(productId, userId);
        return order;
    }

    //有blockHandler优先处理,没有blockHandler,再处理
    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order", fallback = "seckillFallback")
    public Order seckill(@RequestParam(value = "userId", required = false) Long userId,
                             @RequestParam(value = "productId", defaultValue = "888") Long productId) {
        Order order = orderService.createOrder(productId, userId);
        return order;
    }

    public Order seckillFallback(Long userId,
                                 Long productId, Throwable exception) {
        System.out.println("seckillFallback...");
        Order order = new Order();
        order.setId(productId);
        order.setUserId(userId);
        order.setTotalAmount(new BigDecimal("0"));
        order.setAddress("异常信息:" + exception.getClass());
        return order;
    }

    @GetMapping("writeDb")
    public String writeDb() {
        log.info("order writeDb");
        return "order writeDb success....";
    }

    @GetMapping("readDb")
    public String readDb(@RequestHeader(value = "X-Request-Abc", required = false) String xRequestAbc) {
        log.info("order readDb");
        return "order readDb success...." + xRequestAbc;
    }


}
